from django.shortcuts import render

# Create your views here.

from rest_framework import serializers

from utils.viewset import CustomModelViewSet
from .models import BugHandle, BugManage


class BugHandleSerializer(serializers.ModelSerializer):
    """
    bug处理记录 序列化器
    """

    class Meta:
        model = BugHandle
        fields = '__all__'


class BugManageSerializer(serializers.ModelSerializer):
    """
    bug管理 序列化器
    """
    interface_url = serializers.StringRelatedField(source='interface.url', read_only=True)
    handle = BugHandleSerializer(many=True, source="bughandle_set", read_only=True)

    class Meta:
        model = BugManage
        fields = '__all__'


class BugManageListSerializer(serializers.ModelSerializer):
    """
    bug管理 list-序列化器
    """
    interface_url = serializers.StringRelatedField(source='interface.url', read_only=True)

    class Meta:
        model = BugManage
        fields = ['interface_url', 'create_time', 'desc', 'status', 'user', 'id']


class BugManageView(CustomModelViewSet):
    """bug管理的视图"""
    queryset = BugManage.objects.all()
    # 序列化器类
    serializer_class = BugManageSerializer
    list_serializer_class = BugManageListSerializer
    denied_methods = ['delete']     # 禁止删除请求

    def create(self, request, *args, **kwargs):
        """自定义的bug提交处理方法"""
        # 创建一条bug数据
        result = super().create(request, *args, **kwargs)

        bug = BugManage.objects.get(id=result.data['data']['id'])
        handle_info = "提交bug,bug的状态是{}".format(result.data['data'].get('status'))
        # 新增一条bug记录
        BugHandle.objects.create(bug=bug, handle=handle_info, update_user=request.user.username)

        return result

    def update(self, request, *args, **kwargs):
        # 修改bug相关信息
        result = super().update(request, *args, **kwargs)
        bug = self.get_object()
        # 新增一条bug处理记录
        handle_info = "修改bug,bug的状态为{}".format(result.data.get('status'))
        # 新增一条bug记录
        BugHandle.objects.create(bug=bug, handle=handle_info, update_user=request.user.username)
        return result
